#! /usr/bin/env python2.7
# -*- coding: UTF-8 -*-

import os
import sys
import json
import hashlib
import time
from urllib import quote

'''
    rom_ota_info.json:
        {
            "desc":....,
            "sys_version_name":"VINCI_0.2",
            "package":{
                "sys_version_0.1":
                {
                    "force":...., #是否强制,粒度在版本上，这个版本必须升级了
                    "is_full":False #是否全量升级包
                    "addr":"http://.....",
                    "hash":"xxxxx",
                    "length":1234   #文件大小
                },
                "sys_version_0.2":
                {
                    "force":...., #是否强制
                    "is_full":False #是否全量升级包
                    "addr":"http://.....",
                    "hash":"xxxxx",
                    "length":1234   #文件大小
                }...
            }
        }
'''


def gen(version, file_path):
    ret_dict = {
        'sys_version_name': version,
        'package': {},
    }

    with open(os.path.join(file_path, 'description.txt'), 'r') as f:
        ret_dict['desc'] = f.read()

    file_names = [x for x in os.listdir(file_path) if x.split('.')[-1] == 'zip']
    for file_name in file_names:
        device_version = file_name.split('==')[0]
        foo_file = os.path.join(file_path, file_name)
        if foo_file == "%s.zip" % (version,):
            is_full_rom = True
        else:
            is_full_rom = False
        with open(foo_file, 'r') as f:
            ret_dict['package'][device_version] = {
                'addr': 'http://inspero-rom-update-ossbucket.oss-cn-beijing.aliyuncs.com/%s' % quote(
                    'rom-' + version + '/' + file_name),
                'hash': hashlib.md5(f.read()).hexdigest(),
                'length': os.path.getsize(foo_file),
                'force': False,
            }

    with open('rom_ota_info.json', 'w') as f:
        json.dump(ret_dict, f, indent=4, sort_keys=True)


def main():
    arg_list = sys.argv[1:]
    if len(arg_list) > 2:
        print 'too much args'
        return
    if len(arg_list) < 2:
        print 'missing args'
        return
    gen(arg_list[0], arg_list[1])
    print 'finish'
    return


if __name__ == '__main__':
    # gen('1.4.1', '/workspace/share/ota/1.4.3')
    main()